<!--
  * 外包人员信息
  *
  * @Author:    zzw
  * @Date:      2024-09-23 10:25:33
  * @Copyright  jz
-->
<template>
    <a-modal
        :title="form.id ? '编辑' : '添加'"
        width="800px"
        :open="visibleFlag"
        @cancel="onClose"
        :maskClosable="false"
        :destroyOnClose="true"
    >
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }" >
  
            <a-row>
                  <a-col :span="12">
                        <a-form-item label="姓名"  name="name">
                          <a-input style="width: 100%" :disabled="disabled" v-model:value="form.name" placeholder="姓名" />
                        </a-form-item>
                  </a-col>
                  <a-col :span="12">
                        <a-form-item label="年龄"  name="age">
                          <a-input-number :disabled="disabled" style="width: 100%" v-model:value="form.age" placeholder="年龄" />
                        </a-form-item>
                  </a-col>
                  <a-col :span="12">
                        <a-form-item label="性别"  name="gender">
                          <a-radio-group v-model:value="form.gender" :disabled="disabled" >
                            <a-radio :value="'男'">男</a-radio>
                            <a-radio :value="'女'">女</a-radio>
                          </a-radio-group>
                          <!-- <a-input :disabled="disabled" style="width: 100%" v-model:value="form.gender" placeholder="性别" /> -->
                        </a-form-item>
                  </a-col>
                  <a-col :span="12">
                        <a-form-item label="身份证号"  name="idCardNumber">
                          <a-input :disabled="disabled" style="width: 100%" v-model:value="form.idCardNumber" placeholder="身份证号" />
                        </a-form-item>
                  </a-col>
                  <a-col :span="12">
                        <a-form-item label="手机号码"  name="mobilePhone">
                          <a-input :disabled="disabled" style="width: 100%" v-model:value="form.mobilePhone" placeholder="手机号码" />
                        </a-form-item>
                  </a-col>
                  <a-col :span="12">
                        <a-form-item label="紧急联系人"  name="emergencyContact">
                          <a-input :disabled="disabled" style="width: 100%" v-model:value="form.emergencyContact" placeholder="紧急联系人" />
                        </a-form-item>
                  </a-col>
                  <a-col :span="12">
                        <a-form-item label="紧急联系人电话"  name="emergencyContactNum">
                          <a-input :disabled="disabled" style="width: 100%" v-model:value="form.emergencyContactNum" placeholder="紧急联系人电话" />
                        </a-form-item>
                  </a-col>
                  
                  <a-col :span="12">
                        <a-form-item label="所属班组"  name="groupLeaderId">
                          <a-select
                            v-model:value="form.groupLeaderId"
                            placeholder="所属班组"
                            style="width: 100%"
                            :options="departmentOptions"
                            :disabled="disabled" 
                          ></a-select>
                        </a-form-item>
                  </a-col>
                  <a-col :span="12">
                        <a-form-item label="外包公司名称"  name="companyId">
                          <a-select
                            v-model:value="form.companyId"
                            placeholder="外包公司名称"
                            style="width: 100%"
                            :options="companyIdOptions"
                            :disabled="disabled" 
                          ></a-select>
                        </a-form-item>
                  </a-col>
                  
                  <a-col :span="12">
                        <a-form-item label="备注"  name="remark">
                          <!-- <a-input style="width: 100%" v-model:value="form.remark" placeholder="备注" /> -->
                          <a-textarea :disabled="disabled" v-model:value="form.remark" placeholder="备注" allow-clear />
                        </a-form-item>
                  </a-col>
                  <a-col :span="12" id="pic">
                    
                        <a-form-item label="身份证照片"  name="idCardPhoto">
                          <a-image
                          v-if="form.idCardPhoto"
                            :width="200"
                            :src="form.idCardPhoto"
                          />
                          <a-upload :before-upload="beforeUpload" :show-upload-list="false">
                            <a-button :disabled="disabled">
                              <upload-outlined></upload-outlined>
                              上传
                            </a-button>
                          </a-upload>
                          
                        </a-form-item>
                  </a-col>
            </a-row>
      </a-form>
  
      <template #footer>
        <a-space>
          <a-button @click="onClose">取消</a-button>
          <a-button v-if="!disabled" type="primary" @click="onSubmit">保存</a-button>
        </a-space>
      </template>
    </a-modal>
  </template>
  <script setup>
    import { reactive, ref, nextTick,onMounted } from 'vue';
    import _ from 'lodash';
    import { message } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { outsourcingPersonnelApi } from '/@/api/Outsourcing/personnelManagement/index';
    import { smartSentry } from '/@/lib/smart-sentry';
    import { useUserStore } from '/@/store/modules/system/user';
  
    // ------------------------ 事件 ------------------------
  
    const emits = defineEmits(['reloadList']);
  
    // ------------------------ 显示与隐藏 ------------------------
    // 是否显示
    const visibleFlag = ref(false);
    const disabled = ref(false)
    function show(rowData,d) {
      if(d&&d=='detail'){
        disabled.value = true;
      }else{
        disabled.value = false;
      }
      Object.assign(form, formDefault);
      if (rowData && !_.isEmpty(rowData)) {
        Object.assign(form, rowData);
      }
      visibleFlag.value = true;
      nextTick(() => {
        formRef.value.clearValidate();
      });
    }
  
    function onClose() {
      Object.assign(form, formDefault);
      visibleFlag.value = false;
    }
  
    // ------------------------ 表单 ------------------------
  
    // 组件ref
    const formRef = ref();
  
    const formDefault = {
            id: undefined,
                name: undefined, //姓名
                age: undefined, //年龄
                gender: undefined, //性别
                idCardNumber: undefined, //身份证号
                mobilePhone: undefined, //手机号码
                emergencyContact: undefined, //紧急联系人
                emergencyContactNum: undefined, //紧急联系人电话
                idCardPhoto: undefined, //身份证照片（存储为Base64编码）
                groupLeaderId: undefined, //所属班组
                companyId: undefined, //外包公司ID
                remark: undefined, //备注
    };
  
    let form = reactive({ ...formDefault });
  
    const rules = {
                    name: [{ required: true, message: '姓名 必填' }],
                    age: [{ required: true, message: '年龄 必填' }],
                    gender: [{ required: true, message: '性别 必填' }],
                    idCardNumber: [{ required: true, message: '身份证号 必填' }],
                    mobilePhone: [{ required: true, message: '手机号码 必填' }],
                    companyId: [{ required: true, message: '外包公司ID 必填' }],
    };
  
    // 点击确定，验证表单
    async function onSubmit() {
      try {
        await formRef.value.validateFields();
        save();
      } catch (err) {
        message.error('参数验证错误，请仔细填写表单数据!');
      }
    }
  
    // 新建、编辑API
    async function save() {
      if(disabled.value){
        onClose();
        return
      }
      SmartLoading.show();
      try {
        if (form.id) {
          await outsourcingPersonnelApi.update(form);
        } else {
          await outsourcingPersonnelApi.add(form);
        }
        message.success('操作成功');
        emits('reloadList');
        onClose();
      } catch (err) {
        smartSentry.captureError(err);
      } finally {
        SmartLoading.hide();
      }
    }
    // 身份证图片
    function fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          resolve(event.target.result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file); // 读取文件为DataURL
      });
    }
    
    const beforeUpload = async (file) => {
      form.idCardPhoto = await fileToBase64(file);
      return false;
    };
    // 获取外包公司下拉
    const companyIdOptions = ref([])
    async function getCompanyId(){
      let res = await outsourcingPersonnelApi.queryAll();
      companyIdOptions.value = res.data.map(item=>{
        return {
          value:item.id,
          label:item.name
        }
      })
    }
    // 获取班组下拉ww
    const departmentOptions = ref([])
    async function getDepartmentOptions(){
      let departmentId = useUserStore().departmentId;
      let res = await outsourcingPersonnelApi.getDepartment(departmentId);
      departmentOptions.value = res.data.map(item=>{
        return {
          value:item.employeeId,
          label:item.actualName
        }
      })
    }

    onMounted(()=>{
      getCompanyId();
      getDepartmentOptions();
    })
    defineExpose({
      show,
    });
  </script>
  <style scoped>
  #pic .avatar-uploader  .ant-upload {
    width: 128px;
    height: 128px;
    background-color: red;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px !important;
    color: #999 !important; 
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px !important;
    color: #666 !important;
  }
  </style>
  